#include "sgl.h"
#include "SDL.h"
#include <stdio.h>

//设置每个像素的放大比例
#define AMPLIFY_SIZE    1


sgl_color_t frame_buffer[SGL_CONFIG_PANEL_YRES * SGL_CONFIG_PANEL_XRES * AMPLIFY_SIZE * AMPLIFY_SIZE] = {0};


int sdl_show_windows(SDL_Window **m_window, SDL_Renderer **m_renderer)
{
    if ( SDL_CreateWindowAndRenderer( SGL_CONFIG_PANEL_XRES * AMPLIFY_SIZE , SGL_CONFIG_PANEL_YRES* AMPLIFY_SIZE, SDL_WINDOW_SHOWN,
                                      &(*m_window), &(*m_renderer )) != 0 )
        return -1;

    // Clear the window with a black background
    SDL_SetRenderDrawColor( *m_renderer, 0, 0, 0, 255);
    SDL_RenderClear( *m_renderer );

    /* 设置背景为白色 */
    uint32_t *p = (uint32_t*)frame_buffer;
    for(int i = 0; i < SGL_CONFIG_PANEL_YRES * SGL_CONFIG_PANEL_XRES * AMPLIFY_SIZE * AMPLIFY_SIZE; i++) {
        *p =  0XFFFFFF; // white
        p++;
    }
    // Show the window
    SDL_RenderPresent( *m_renderer );
    return 0;
}

static void sgl_disp_pixel(int16_t x, int16_t y, sgl_color_t color)
{
    for(int i = 0; i < AMPLIFY_SIZE; i ++ )
    {
        for(int j = 0; j < AMPLIFY_SIZE ; j ++)
        {
           frame_buffer[(y*SGL_CONFIG_PANEL_XRES*AMPLIFY_SIZE*AMPLIFY_SIZE + x*AMPLIFY_SIZE) + i*SGL_CONFIG_PANEL_XRES*AMPLIFY_SIZE + j].blue =  (color.blue)&0xFF;
           frame_buffer[(y*SGL_CONFIG_PANEL_XRES*AMPLIFY_SIZE*AMPLIFY_SIZE + x*AMPLIFY_SIZE) + i*SGL_CONFIG_PANEL_XRES*AMPLIFY_SIZE + j].green =  (color.green)&0xFF;
           frame_buffer[(y*SGL_CONFIG_PANEL_XRES*AMPLIFY_SIZE*AMPLIFY_SIZE + x*AMPLIFY_SIZE) + i*SGL_CONFIG_PANEL_XRES*AMPLIFY_SIZE + j].red =  (color.red)&0xFF;
           frame_buffer[(y*SGL_CONFIG_PANEL_XRES*AMPLIFY_SIZE*AMPLIFY_SIZE + x*AMPLIFY_SIZE) + i*SGL_CONFIG_PANEL_XRES*AMPLIFY_SIZE + j].alpha = (color.alpha)&0xFF;
        }
    }
}

void sgl_disp_area(int16_t x1, int16_t y1, int16_t x2, int16_t y2, const sgl_color_t *src)
{
    const sgl_color_t *color = src;
    int16_t x = x1, y = y1, hight = y2 - y1, width = x2 - x1;
    for(int i = y; i < (hight + y); i++ )
    {
        for(int j = x; j < (width + x) ; j ++ )
        {
           sgl_disp_pixel(j, i, *color);
           color ++;
        }
    }
}

void update_win(SDL_Renderer * m_renderer)
{
    auto texture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, SGL_CONFIG_PANEL_XRES * AMPLIFY_SIZE, SGL_CONFIG_PANEL_YRES * AMPLIFY_SIZE);
    SDL_UpdateTexture(texture, NULL, frame_buffer, SGL_CONFIG_PANEL_XRES * AMPLIFY_SIZE * 4);
    SDL_RenderCopy(m_renderer, texture, NULL, NULL);
    SDL_RenderPresent(m_renderer);
}
